package com.xiaomai.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.xiaomai.oss.service.OssService;
import com.xiaomai.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String upload(MultipartFile file) {
        String endpoint = ConstantPropertiesUtils.END_POINT;
// 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName =ConstantPropertiesUtils.BUCKET_NAME;
        String fileName = file.getOriginalFilename();

        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String dataPath = new DateTime().toString("yyyy/MM/dd");
        fileName = dataPath+"/"+uuid + fileName;


        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            InputStream inputStream = file.getInputStream();
            ossClient.putObject(bucketName, fileName, inputStream);
            ossClient.shutdown();
            String upLoadUrl="http://" + bucketName + "." + endpoint + "/" + fileName;
            return upLoadUrl;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }
}
